package com.va1m.demo.service.impl;

import com.va1m.demo.entity.Member;
import com.va1m.demo.entity.Record;
import com.va1m.demo.entity.User;
import com.va1m.demo.mapper.MemberMapper;
import com.va1m.demo.mapper.RecordMapper;
import com.va1m.demo.mapper.UserMapper;
import com.va1m.demo.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 处理会员充值的service
 * @author Admin
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MemberServiceImpl implements MemberService {
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public List<Member> getMemberList() {
        return memberMapper.selectList(null);
    }

    @Override
    public Boolean recharge(Integer memberId, Integer userId) {
        //根据id 查询将要充值的会员信息(金额和时长)
        Member member = memberMapper.selectById(memberId);
        //根据用户id 查询用户的信息
        User user = userMapper.selectById(userId);
        //新增一条消费记录
        //补全消费记录信息 金额 时间 所属用户id
        Record record = new Record();
        record.setAmount(member.getAmount());
        record.setDate(new Date());
        record.setUserId(userId);
        int insertRecord = recordMapper.insert(record);
        //添加失败时抛出异常回滚
        if(insertRecord <= 0){
            throw new RuntimeException("充值失败请重试");
        }
        //设置会员过期时间
        Calendar calendar = Calendar.getInstance();
        //获取用户当前的过期时间
        Date expireDate = user.getExpireDate();
        //如果从未充值过 则将过期时间设置为当前时间
        if(expireDate == null){
            expireDate = new Date();
        }
        calendar.setTime(expireDate);
        calendar.add(Calendar.MONTH, member.getActiveTime());
        //修改用户信息 余额 会员过期时间
        Integer updateUserInfo = userMapper.updateUserInfo(userId, member.getAmount(), calendar.getTime());
        //修改失败抛出异常回滚
        if(updateUserInfo <= 0){
            throw new RuntimeException("充值失败请重试");
        }
        return true;
    }
}
